package com.lc.luzhengtang.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;
import com.lc.luzhengtang.BaseApplication;
import com.lc.luzhengtang.R;
import com.lc.luzhengtang.bean.CommenBean;
import com.lc.luzhengtang.bean.UserBean;
import com.lc.luzhengtang.conn.Conn;
import com.lc.luzhengtang.conn.ConnBindWx;
import com.lc.luzhengtang.conn.ConnChangeSex;
import com.lc.luzhengtang.conn.ConnPersonalInfo;
import com.lc.luzhengtang.conn.ConnUnBindWx;
import com.lc.luzhengtang.conn.JsonSetavatar;
import com.lc.luzhengtang.util.LovelyToast;
import com.lc.luzhengtang.util.RSAUtils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.scale.ScaleScreenHelperFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/5/5.
 */
public class ChangeDataActivity extends TakePhotoActivity {
    private static final String TAG = "ChangeDataActivity";
    @BindView(R.id.img_news)
    ImageView imgNews;
    @BindView(R.id.mine_head_iv)
    SimpleDraweeView mineHeadIv;
    @BindView(R.id.text_nickname)
    TextView textNickname;
    @BindView(R.id.text_phone)
    TextView textPhone;
    @BindView(R.id.text_username)
    TextView textUsername;
    @BindView(R.id.text_sex)
    TextView textSex;
    @BindView(R.id.text_email)
    TextView textEmail;
    @BindView(R.id.text_qq)
    TextView textQq;
    @BindView(R.id.btn_complete)
    Button btnComplete;
    @BindView(R.id.layout_nickname)
    LinearLayout layoutNickname;
    @BindView(R.id.layout_tel)
    LinearLayout layoutTel;
    @BindView(R.id.layout_name)
    LinearLayout layoutName;
    @BindView(R.id.layout_sex)
    LinearLayout layoutSex;
    @BindView(R.id.layout_email)
    LinearLayout layoutEmail;
    @BindView(R.id.layout_qq)
    LinearLayout layoutQq;
    @BindView(R.id.text_wx)
    TextView textWx;
    @BindView(R.id.layout_wx)
    LinearLayout layoutWx;
    @BindView(R.id.text_unbind_wx)
    TextView textUnbindWx;
    @BindView(R.id.layout_unbind_wx)
    LinearLayout layoutUnbindWx;
    @BindView(R.id.btn_unbindwx)
    Button btnUnbindwx;
    @BindView(R.id.text_tuijian)
    TextView textTuijian;
    @BindView(R.id.layout_tuijiancode)
    LinearLayout layoutTuijiancode;
    @BindView(R.id.text_tuijianren)
    TextView textTuijianren;
    @BindView(R.id.layout_tuijianren)
    LinearLayout layoutTuijianren;
    @BindView(R.id.btn_bind_wx)
    Button btnBindWx;

    private PopupWindow popWindow, popWindow2;
    private TextView etname, tv01, tv02, tv03;
    private String PATH;
    private String picStr = "";

    private String avatar = "";

    String sex;

    String get_id = BaseApplication.basePreferences.readUid();

    String mi;
    String ming;


    String openid;
    String pic_url;
    String name;
    UMAuthListener authListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
//            SocializeUtils.safeShowDialog(dialog);
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
//            SocializeUtils.safeCloseDialog(dialog);、



            try {
                String temp = "";
                for (String key : data.keySet()) {
                    temp = temp + key + " : " + data.get(key) + "\n";
                    Log.d(data.get(key), "ggggggggggggggggggggggg");
                }
                openid = data.get("openid");
                pic_url = data.get("iconurl");
                name = data.get("name");
                getBindWx();

            }catch (Exception e){

            }


           /* data.get("unionid"), data.get("screen_name"),
                    data.get("city"), data.get("openid"), data.get("country"), data.get("iconurl"),
                    data.get("language"), data.get("province"), data.get("gender")*/


        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
//            SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(ChangeDataActivity.this, "失败：" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
//            SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(ChangeDataActivity.this, "取消了", Toast.LENGTH_LONG).show();
        }
    };
    private File mOutputImage;
    private Uri imageUri;


    //    open_id
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        View contentView = LayoutInflater.from(this).inflate(R.layout.activity_changedata, null);
        ScaleScreenHelperFactory.getInstance().loadView(((ViewGroup) contentView));
        setContentView(contentView);
        ButterKnife.bind(this);


        if (getIntent().getStringExtra("open_id").equals("已绑定微信")) {
            layoutUnbindWx.setVisibility(View.GONE);
            btnBindWx.setVisibility(View.GONE);
            btnUnbindwx.setVisibility(View.VISIBLE);
        } else {
            layoutUnbindWx.setVisibility(View.GONE);
            layoutWx.setVisibility(View.VISIBLE);
            btnUnbindwx.setVisibility(View.GONE);
            btnBindWx.setVisibility(View.VISIBLE);
        }



        //  mineHeadIv.setImageURI(Uri.parse("http://img1.imgtn.bdimg.com/it/u=1794894692,1423685501&fm=23&gp=0.jpg"));
        // TODO Auto-generated method stub
//        HashMap<String, Object> map = null;
        HashMap<String, Object> map = new HashMap<>();
        map.put("public", "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9EulFoqmkXsbUTYGc/e/dylqJ\n" +
                "eNx3mcLeBTydP6qi5sMmdo2midzq2yPlwKcYW65PZbBF4wowxBdv/+QI96KWwHg5\n" +
                "ZL0jwzIsG+edLwrXshkvTpUgXV4dMUSRH6DMkbcUR9JLAycQIR2SATMo71/j9GpC\n" +
                "3dVclF6SSsaL63fmYQIDAQAB");
        map.put("private", "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAKj84mrllMF7iAEF\n" +
                "9+osdrdQxme1wNJ0kE40OgtXQ7iplKOTCI4/EaTdN7+Ur6dYoW76u+8SA7XTEgI8\n" +
                "9qoNh35+6zE7TaiTJ9gfPdEOS830apvkSk/lWv8xxpOtrqwT1EhdwTvT7FXOMA8c\n" +
                "FIoMEiT7nooDgBC21s8nZEFGdosFAgMBAAECgYEApl+LX2k24qMHjNJeecxa+TJq\n" +
                "lDLKa6ldZdFfkEjTINy8vasGEl4ftewiddkicyT8kzICk2ZuBraPFWsGAvic+x+x\n" +
                "DwtodxYZAsF7pFLCPRcTm/+afkVVvPgJeQD+1sStE/7Qy3RjG0/hzFP1LqqVZI7S\n" +
                "iwU4HIuR6jmyEbTgRSUCQQDgIBfrbthkrT9gkx2s6DqOarcdRbc2HqXdW6pd0Zxf\n" +
                "v+oseO2mj+uL+3m8KoccFb1+itsnlfffeuNQdQp5Nh6nAkEAwQVbGbsSQV9CuMb/\n" +
                "jGMo50fDFn6YkPB0twGWgLeIcFFi+U8Gf4sNGZW8mmLglUdqKnSltO+6W86PraOC\n" +
                "1zHKcwJBANFbyVxIT+VDnJc29ZqF1+UfNGwoqmromCG9tdgrrHoYyMPANqbHe81o\n" +
                "HKAzzb/jYv6o8Oz6fvAIV/zZR+5QKrMCQB2AlREUv9CQH+GgQPUTPvBCzrXEectF\n" +
                "hYFnU7qu0sLgHbGfe43JEiKD+YTbcho/BSIiHCXQsnpP0zQmFtyPdrMCQQCjW4/p\n" +
                "rPkZibJPPHgVRNtcGNt9sza9v+18uNYFIUmf/uAAu2BMnWhjZ9t3uXS8v6xbJ10Y\n" +
                "44B+eXzFp+9pRcG2");
        try {
            map = RSAUtils.getKeys();
            //生成公钥和私钥
            RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
            RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");
//            RSAPublicKey publicKey = (RSAPublicKey) map.get("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9EulFoqmkXsbUTYGc/e/dylqJeNx3mcLeBTydP6qi5sMmdo2midzq2yPlwKcYW65PZbBF4wowxBdv/+QI96KWwHg5ZL0jwzIsG+edLwrXshkvTpUgXV4dMUSRH6DMkbcUR9JLAycQIR2SATMo71/j9GpC3dVclF6SSsaL63fmYQIDAQAB");
//            RSAPrivateKey privateKey = (RSAPrivateKey) map.get("MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAKj84mrllMF7iAEF9+osdrdQxme1wNJ0kE40OgtXQ7iplKOTCI4/EaTdN7+Ur6dYoW76u+8SA7XTEgI89qoNh35+6zE7TaiTJ9gfPdEOS830apvkSk/lWv8xxpOtrqwT1EhdwTvT7FXOMA8cFIoMEiT7nooDgBC21s8nZEFGdosFAgMBAAECgYEApl+LX2k24qMHjNJeecxa+TJqlDLKa6ldZdFfkEjTINy8vasGEl4ftewiddkicyT8kzICk2ZuBraPFWsGAvic+x+xDwtodxYZAsF7pFLCPRcTm/+afkVVvPgJeQD+1sStE/7Qy3RjG0/hzFP1LqqVZI7S iwU4HIuR6jmyEbTgRSUCQQDgIBfrbthkrT9gkx2s6DqOarcdRbc2HqXdW6pd0Zxf v+oseO2mj+uL+3m8KoccFb1+itsnlfffeuNQdQp5Nh6nAkEAwQVbGbsSQV9CuMb/ jGMo50fDFn6YkPB0twGWgLeIcFFi+U8Gf4sNGZW8mmLglUdqKnSltO+6W86PraOC1zHKcwJBANFbyVxIT+VDnJc29ZqF1+UfNGwoqmromCG9tdgrrHoYyMPANqbHe81oHKAzzb/jYv6o8Oz6fvAIV/zZR+5QKrMCQB2AlREUv9CQH+GgQPUTPvBCzrXEectF hYFnU7qu0sLgHbGfe43JEiKD+YTbcho/BSIiHCXQsnpP0zQmFtyPdrMCQQCjW4/p rPkZibJPPHgVRNtcGNt9sza9v+18uNYFIUmf/uAAu2BMnWhjZ9t3uXS8v6xbJ10Y44B+eXzFp+9pRcG2");
            //模
            String modulus = publicKey.getModulus().toString();
            //公钥指数
            String public_exponent = publicKey.getPublicExponent().toString();
            //私钥指数
            String private_exponent = privateKey.getPrivateExponent().toString();
            //明文
            ming = get_id;
            //使用模和指数生成公钥和私钥
            RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus, public_exponent);
            RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus, private_exponent);
            //加密后的密文
            mi = RSAUtils.encryptByPublicKey(ming, pubKey);
            Log.d(mi, "1111111111111111111111111111111");


            System.err.println(mi);
            //解密后的明文
            ming = RSAUtils.decryptByPrivateKey(mi, priKey);
            Log.d(ming, "1111111111111111111111111111111");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        mineHeadIv.setImageURI(Uri.parse(BaseApplication.basePreferences.readAvatar()));
        textNickname.setText(BaseApplication.basePreferences.readUserName());
        textPhone.setText(BaseApplication.basePreferences.readMobile());
        textUsername.setText(BaseApplication.basePreferences.readName());
        textSex.setText(BaseApplication.basePreferences.readSex());
        textEmail.setText(BaseApplication.basePreferences.readEmail());
        textQq.setText(BaseApplication.basePreferences.readQq());
        textTuijianren.setText(BaseApplication.basePreferences.readTuijian());
    }

    @OnClick({R.id.img_news, R.id.mine_head_iv, R.id.text_nickname, R.id.text_phone, R.id.text_username, R.id.text_sex, R.id.text_email, R.id.text_qq, R.id.btn_complete, R.id.layout_nickname, R.id.layout_tel, R.id.layout_name, R.id.layout_sex, R.id.layout_email, R.id.layout_qq, R.id.text_wx, R.id.layout_wx, R.id.text_unbind_wx, R.id.layout_unbind_wx, R.id.btn_unbindwx, R.id.text_tuijian, R.id.layout_tuijiancode, R.id.text_tuijianren, R.id.layout_tuijianren, R.id.btn_bind_wx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_news:
                finish();
                break;
            case R.id.mine_head_iv:

                showPopupWindow(mineHeadIv);

                break;
            case R.id.text_nickname:

                break;
            case R.id.text_phone:

                break;
            case R.id.text_username:

                break;
            case R.id.text_sex:

                break;
            case R.id.text_email:

                break;
            case R.id.text_qq:

                break;
            case R.id.btn_complete:
                break;

            case R.id.layout_nickname:
                //昵称
                startActivity(new Intent(ChangeDataActivity.this, ChangeNickNameActivity.class));

                break;
            case R.id.layout_tel:
                //电话
                startActivity(new Intent(ChangeDataActivity.this, ChangePhoneActivity.class));
                break;
            case R.id.layout_name:
                //姓名
                startActivity(new Intent(ChangeDataActivity.this, ChangeUsernameActivity.class));

                break;
            case R.id.layout_sex:
//                startActivity(new Intent(ChangeDataActivity.this, ChangeSexActivity.class));
                showPopupWindow2(layoutSex);

                break;
            case R.id.layout_email:
                startActivity(new Intent(ChangeDataActivity.this, ChangeEmailActivity.class));
                break;
            case R.id.layout_qq:
                startActivity(new Intent(ChangeDataActivity.this, ChangeQqActivity.class));
                break;


            case R.id.text_wx:
//                startActivity(new Intent(ChangeDataActivity.this, BindWxActivity.class));
                UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, authListener);
                break;
            case R.id.layout_wx:


                break;


            case R.id.text_unbind_wx:
                break;
            case R.id.layout_unbind_wx:
                unBindWx();
                break;


            case R.id.btn_unbindwx:

                unBindWx();
                break;


            case R.id.text_tuijian:

                break;

            case R.id.layout_tuijiancode:
                break;


            case R.id.text_tuijianren:
                break;
            case R.id.layout_tuijianren:
                startActivity(new Intent(ChangeDataActivity.this, SettingsTuijianActivity.class));

                break;

            case R.id.btn_bind_wx:
                UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, authListener);
//                UMShareAP I.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, authListener);

                break;

        }
    }


    public void unBindWx() {
        new ConnUnBindWx(BaseApplication.basePreferences.readUid(), new AsyCallBack<CommenBean>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                super.onSuccess(toast, type, o, commenBean);
                if (commenBean.getCode()==200){

                    LovelyToast.makeText(ChangeDataActivity.this, commenBean.getMessage(), 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                    UMShareAPI.get(ChangeDataActivity.this).deleteOauth(ChangeDataActivity.this, SHARE_MEDIA.WEIXIN, authListener);
                    layoutUnbindWx.setVisibility(View.GONE);
                    layoutWx.setVisibility(View.VISIBLE);
                    btnUnbindwx.setVisibility(View.GONE);
                    btnBindWx.setVisibility(View.VISIBLE);
                }else {
                    LovelyToast.makeText(ChangeDataActivity.this, commenBean.getMessage(), 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                }

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
            }
        }


        ).execute(ChangeDataActivity.this, false);
    }


    public void getBindWx() {
        new ConnBindWx(BaseApplication.basePreferences.readUid(), openid, new AsyCallBack<CommenBean>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                super.onSuccess(toast, type, o, commenBean);
                if (commenBean.getCode() == 400) {
                    LovelyToast.makeText(ChangeDataActivity.this, commenBean.getMessage(), 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
//                   UMShareAPI.get(ChangeDataActivity.this).deleteOauth(ChangeDataActivity.this, SHARE_MEDIA.WEIXIN, authListener);
                } else {
                    LovelyToast.makeText(ChangeDataActivity.this, commenBean.getMessage(), 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                    btnUnbindwx.setVisibility(View.VISIBLE);
                    btnBindWx.setVisibility(View.GONE);
                }

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
            }
        }


        ).execute(ChangeDataActivity.this, false);
    }


    private void showPopupWindow2(View parent) {
        if (popWindow2 == null) {

            View view = ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) LayoutInflater.from(this).inflate(R.layout.pop_sex, null));
            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow2 = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop2(view);
        }
        //设置动画效果
        popWindow2.setAnimationStyle(android.R.style.Animation_InputMethod);
        //获取popwindow焦点
        popWindow2.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow2.setOutsideTouchable(true);
        popWindow2.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow2.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow2.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    public void initPop2(View view) {
        tv01 = (TextView) view.findViewById(R.id.tv_01);//拍照
        tv02 = (TextView) view.findViewById(R.id.tv_02);//相册

        LinearLayout layout_picselected = (LinearLayout) view.findViewById(R.id.layout_picselected);
        layout_picselected.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow2.dismiss();
            }
        });

        tv01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow2.dismiss();
                textSex.setText(tv01.getText().toString());
                sex = tv01.getText().toString();
                setSex();
            }
        });
        tv02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow2.dismiss();
                textSex.setText(tv02.getText().toString());
                sex = tv02.getText().toString();
                setSex();
            }
        });

    }


    public void setSex() {


        new ConnChangeSex(BaseApplication.basePreferences.readUid(), sex, new AsyCallBack<CommenBean>() {
            @Override
            public void onSuccess(String toast, int type, Object o, CommenBean changeNickName) throws Exception {
                super.onSuccess(toast, type, o, changeNickName);
                LovelyToast.makeText(ChangeDataActivity.this, changeNickName.getMessage(), 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
                BaseApplication.basePreferences.saveSex(sex);
                popWindow2.dismiss();
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                popWindow2.dismiss();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                popWindow2.dismiss();
            }
        }

        ).execute(ChangeDataActivity.this, false);

    }


//    @Override
//    protected void resultPhotoPath(ImageView imageView, final String s) {
//       /* if (!TextUtils.isEmpty(s)) {
//            PATH = s;
//
//            mineHeadIv.setVisibility(View.VISIBLE);
//            mineHeadIv.setImageURI(Uri.parse("file:///" + s));
//
//
//            Log.e("DDDDDDDDDD", s);
//
//            initUpload();
//        }*/
//        mineHeadIv.setImageURI(Uri.parse("file:///" + s));
//
//        try {
//
////            picStr = getEncode64(s);
//            picStr = Base64Util.encodeBase64File(s);
//
//            Log.d(ming, "77777777777777777777777777");
//            new JsonSetavatar(BaseApplication.basePreferences.readUid(), new File(s), new AsyCallBack<CommenBean>() {
//                @Override
//                public void onSuccess(String toast, int type, CommenBean info) throws Exception {
//                    if (info != null) {
////                    MyApplication.myPreferences.saveUserpic(info.avatar);
////                    ivcamera.setSelected(true);
//                        //  BaseApplication.basePreferences.saveAvatar(info.getMessage());
//                        mineHeadIv.setSelected(true);
//                        getUserData();
//                      /*  BaseApplication.basePreferences.saveAvatar(picStr);
//                        mineHeadIv.setImageURI(Uri.parse(Conn.HOST2 + BaseApplication.basePreferences.readAvatar()));*/
//                        LovelyToast.makeText(ChangeDataActivity.this, "上传头像成功", 0, LovelyToast
//                                .SUCCESS, LovelyToast.SCALE);
//
//                    }
//                }
//
//                @Override
//                public void onEnd(String toast, int type) throws Exception {
//                    //     UtilToast.show(PersonalSettingsActivity.this, JsonSetavatar.TOAST);
//                }
//            }).execute(this, true);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    private void initUpload() {
        Log.d(getEncode64(PATH), "aaaaaaaaaaaaaaaa");
        Log.d(getEncode64(PATH), "bbbbbbbbbbbbbbbb");


    }

    public void getUserData() {
        Log.d(BaseApplication.basePreferences.readUid(), "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq");
        Log.d(BaseApplication.basePreferences.readUid(), "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq");
        new ConnPersonalInfo(BaseApplication.basePreferences.readUid(), new AsyCallBack<UserBean>() {


            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);

            }

            @Override
            public void onSuccess(String toast, int type, Object o, UserBean userBean) throws Exception {
                super.onSuccess(toast, type, o, userBean);

                if (TextUtils.isEmpty(userBean.getData().getUsername())) {
                    textUsername.setText(userBean.getData().getMobile());
                }
//

                textUsername.setText(userBean.getData().getUsername());

                mineHeadIv.setImageURI(Conn.HOST3 + Uri.parse(userBean.getData().getAvatar()));
                BaseApplication.basePreferences.saveAvatar(userBean.getData().getAvatar());

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);

            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);

            }
        }
        ).execute(ChangeDataActivity.this, false);
    }

    public static String getEncode64(String path) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bStream);
        bitmap.recycle();
        byte[] bytes = bStream.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

//    @Override
//    protected AppCrop getCrop() {
//        return new AppCrop().setCrop(true);
//    }


    private void showPopupWindow(View parent) {
        if (popWindow == null) {
        /*    View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(this)
                    .inflate(R.layout.pop_select_photo2, null)));*/
//ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) convertView);
//            LayoutInflater.from(this).inflate(R.layout.pop_select_photo2,null)
            View view = ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) LayoutInflater.from(this).inflate(R.layout.pop_select_img, null));
            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop(view);
        }
        //设置动画效果
        popWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
        //获取popwindow焦点
        popWindow.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    private CropOptions getCropOptions() {
//        if(rgCrop.getCheckedRadioButtonId()!=R.id.rbCropYes)return null;
        int height = 100;
        int width = 100;
        boolean withWonCrop = true;

        CropOptions.Builder builder = new CropOptions.Builder();

//        if(rgCropSize.getCheckedRadioButtonId()==R.id.rbAspect){
        builder.setAspectX(width).setAspectY(height);
//        }else {
//        builder.setOutputX(width).setOutputY(height);
//        }
        builder.setWithOwnCrop(true);
        return builder.create();
    }

    public void initPop(View view) {
        tv01 = (TextView) view.findViewById(R.id.tv_01);//拍照
        tv02 = (TextView) view.findViewById(R.id.tv_02);//相册
        tv03 = (TextView) view.findViewById(R.id.tv_03);//取消
        LinearLayout layout_picselected = (LinearLayout) view.findViewById(R.id.layout_picselected);
        layout_picselected.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });

        String pictureName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.getDefault()).format(new Date()) +
                "-" + System.currentTimeMillis() + ".jpg";

        mOutputImage = new File(getExternalCacheDir(), pictureName);
        imageUri = Uri.fromFile(mOutputImage);


//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            imageUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", mOutputImage);
//
//            Log.e(TAG, imageUri.getPath());
//        } else {
//            imageUri = Uri.fromFile(mOutputImage);
//        }


        tv01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow.dismiss();
                getTakePhoto().onPickFromCaptureWithCrop(imageUri, getCropOptions());
//                startCamera(mineHeadIv);

            }
        });
        tv02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow.dismiss();
                getTakePhoto().onPickFromGalleryWithCrop(imageUri, getCropOptions());
//                startAlbum(mineHeadIv);
            }
        });
        tv03.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow.dismiss();
            }
        });
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        String path = result.getImage().getOriginalPath();

        mineHeadIv.setImageURI(Uri.parse("file:///" + path));


        new JsonSetavatar(BaseApplication.basePreferences.readUid(), new File(path), new AsyCallBack<CommenBean>() {
            @Override
            public void onSuccess(String toast, int type, CommenBean info) throws Exception {
                if (info != null) {
//                    MyApplication.myPreferences.saveUserpic(info.avatar);
//                    ivcamera.setSelected(true);
                    //  BaseApplication.basePreferences.saveAvatar(info.getMessage());
                    mineHeadIv.setSelected(true);
                    getUserData();
                      /*  BaseApplication.basePreferences.saveAvatar(picStr);
                        mineHeadIv.setImageURI(Uri.parse(Conn.HOST2 + BaseApplication.basePreferences.readAvatar()));*/
                    LovelyToast.makeText(ChangeDataActivity.this, "上传头像成功", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);

                }
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                //     UtilToast.show(PersonalSettingsActivity.this, JsonSetavatar.TOAST);
            }
        }).execute(this, true);
        Log.d(TAG, "path = " + path);

    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    //    @Override
//    protected String getCameraAbsolutePath() {
//        if (UtilSDCard.isSDCardEnable()) {
//            File file = new File(Environment.getExternalStorageDirectory() + "/head");
//            if (!file.exists()) {
//                file.mkdir();
//            }
//        } else {
//            File dir = new File(this.getApplicationInfo().dataDir + "/head/");
//            if (!dir.exists())
//                dir.mkdir();
//            return dir.getAbsolutePath();
//        }
//
//        return Environment.getExternalStorageDirectory() + "/head";
//    }


}
